<template>
  <div class="icon-editor">
    <div class="editor-content">
      <!-- 预览区域 -->
      <div class="preview-section">
        <div class="preview-header">
          <a-typography-title :level="4">实时预览</a-typography-title>
          <a-space>
            <a-button @click="resetToOriginal" size="small">
              <template #icon><undo-outlined /></template>
              重置
            </a-button>
            <a-button type="primary" @click="exportIcon" size="small">
              <template #icon><download-outlined /></template>
              导出
            </a-button>
          </a-space>
        </div>

        <div class="preview-container">
          <!-- 原图预览 -->
          <div class="preview-item">
            <div class="preview-label">原图</div>
            <div class="preview-box original">
              <div class="icon-display" v-html="originalIcon"></div>
            </div>
          </div>

          <!-- 编辑后预览 -->
          <div class="preview-item">
            <div class="preview-label">编辑后</div>
            <div class="preview-box edited">
              <div
                class="icon-display"
                :style="{
                  transform: `scale(${iconSize / 22})`,
                  '--icon-color': iconColor,
                  '--stroke-width': strokeWidth
                }"
                v-html="editedIcon"
              ></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 编辑控制面板 -->
      <div class="controls-section">
        <a-card title="编辑属性" size="small">
          <!-- 图标大小 -->
          <div class="control-group">
            <label class="control-label">图标大小</label>
            <div class="control-content">
              <a-slider v-model:value="iconSize" :min="16" :max="200" :marks="sizeMarks" :tooltip="{ formatter: (v) => `${v}px` }" />
              <a-input-number v-model:value="iconSize" :min="16" :max="200" size="small" style="width: 80px; margin-left: 12px" />
            </div>
          </div>

          <!-- 线条粗细 -->
          <div class="control-group">
            <label class="control-label">线条粗细</label>
            <div class="control-content">
              <a-slider v-model:value="strokeWidth" :min="1" :max="8" :step="0.5" :marks="strokeMarks" :tooltip="{ formatter: (v) => `${v}px` }" />
              <a-input-number v-model:value="strokeWidth" :min="1" :max="8" :step="0.5" size="small" style="width: 80px; margin-left: 12px" />
            </div>
          </div>

          <!-- 图标风格 -->
          <div class="control-group">
            <label class="control-label">图标风格 (颜色)</label>
            <div class="control-content">
              <a-radio-group v-model:value="colorMode" @change="onColorModeChange">
                <a-radio-button value="linear">线性</a-radio-button>
                <a-radio-button value="fill">填充</a-radio-button>
                <a-radio-button value="dual">双色</a-radio-button>
                <a-radio-button value="multi">多色</a-radio-button>
              </a-radio-group>
            </div>
          </div>

          <!-- 描边颜色 -->
          <div class="control-group">
            <label class="control-label">描边颜色</label>
            <div class="control-content">
              <div class="color-picker-group">
                <input type="color" v-model="iconColor" class="color-picker" @change="onColorChange" />
                <a-input v-model:value="iconColor" placeholder="#333333" size="small" style="width: 100px; margin-left: 8px" @change="onColorChange" />
                <a-space style="margin-left: 12px">
                  <a-button size="small" v-for="preset in presetColors" :key="preset" class="preset-color-btn" :style="{ backgroundColor: preset }" @click="setPresetColor(preset)"></a-button>
                </a-space>
              </div>
            </div>
          </div>

          <!-- 填充颜色 (仅填充、双色、多色模式) -->
          <div v-if="['fill', 'dual', 'multi'].includes(colorMode)" class="control-group">
            <label class="control-label">填充颜色</label>
            <div class="control-content">
              <div class="color-picker-group">
                <input type="color" v-model="fillColor" class="color-picker" @change="onFillColorChange" />
                <a-input v-model:value="fillColor" placeholder="#1890ff" size="small" style="width: 100px; margin-left: 8px" @change="onFillColorChange" />
              </div>
            </div>
          </div>

          <!-- 多色调色板 (仅多色模式) -->
          <div v-if="colorMode === 'multi'" class="control-group">
            <label class="control-label">多色配置</label>
            <div class="control-content">
              <div class="multi-color-config">
                <div v-for="(color, index) in multiColors" :key="index" class="multi-color-item">
                  <span class="color-label">颜色 {{ index + 1 }}:</span>
                  <input type="color" v-model="multiColors[index]" class="color-picker small" @change="onMultiColorChange" />
                  <a-input v-model:value="multiColors[index]" size="small" style="width: 90px; margin-left: 8px" @change="onMultiColorChange" />
                </div>
              </div>
            </div>
          </div>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { UndoOutlined, DownloadOutlined } from '@ant-design/icons-vue'

const props = defineProps({
  icon: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['export'])

// 响应式数据
const iconSize = ref(22)
const strokeWidth = ref(4)
const colorMode = ref('linear')
const iconColor = ref('#333333')
const fillColor = ref('#1890ff')
const multiColors = ref(['#ff6b6b', '#4ecdc4', '#45b7d1', '#f9ca24'])
const originalIcon = ref('')

// 预设颜色
const presetColors = ['#333333', '#666666', '#999999', '#cccccc', '#ff4d4f', '#fa541c', '#fa8c16', '#faad14', '#52c41a', '#13c2c2', '#1890ff', '#722ed1', '#eb2f96', '#f5222d']

// 滑块标记
const sizeMarks = {
  16: '16',
  32: '32',
  48: '48',
  64: '64',
  128: '128',
  200: '200'
}

const strokeMarks = {
  1: '1',
  2: '2',
  4: '4',
  6: '6',
  8: '8'
}

// 计算编辑后的图标
const editedIcon = computed(() => {
  if (!originalIcon.value) return ''

  let svg = originalIcon.value

  // 应用颜色和样式变化
  svg = svg.replace(/<svg([^>]*)>/g, (match, attrs) => {
    // 确保有 xmlns 属性
    if (!attrs.includes('xmlns=')) {
      attrs += ' xmlns="http://www.w3.org/2000/svg"'
    }
    return `<svg${attrs}>`
  })

  // 根据颜色模式应用不同的样式
  switch (colorMode.value) {
    case 'linear':
      // 线性模式：只有描边，无填充
      svg = svg.replace(/fill="[^"]*"/g, 'fill="none"')
      svg = svg.replace(/stroke="[^"]*"/g, `stroke="${iconColor.value}"`)
      svg = svg.replace(/stroke-width="[^"]*"/g, `stroke-width="${strokeWidth.value}"`)
      // 如果没有 stroke 属性，添加
      if (!svg.includes('stroke=')) {
        svg = svg.replace(/<path([^>]*)/g, `<path stroke="${iconColor.value}"$1`)
        svg = svg.replace(/<circle([^>]*)/g, `<circle stroke="${iconColor.value}"$1`)
        svg = svg.replace(/<rect([^>]*)/g, `<rect stroke="${iconColor.value}"$1`)
        svg = svg.replace(/<line([^>]*)/g, `<line stroke="${iconColor.value}"$1`)
        svg = svg.replace(/<polyline([^>]*)/g, `<polyline stroke="${iconColor.value}"$1`)
        svg = svg.replace(/<polygon([^>]*)/g, `<polygon stroke="${iconColor.value}"$1`)
      }
      break

    case 'fill':
      // 填充模式：有填充，无描边
      svg = svg.replace(/fill="[^"]*"/g, `fill="${fillColor.value}"`)
      svg = svg.replace(/stroke="[^"]*"/g, 'stroke="none"')
      // 如果没有 fill 属性，添加
      if (!svg.includes('fill=')) {
        svg = svg.replace(/<path([^>]*)/g, `<path fill="${fillColor.value}"$1`)
        svg = svg.replace(/<circle([^>]*)/g, `<circle fill="${fillColor.value}"$1`)
        svg = svg.replace(/<rect([^>]*)/g, `<rect fill="${fillColor.value}"$1`)
      }
      break

    case 'dual':
      // 双色模式：填充 + 描边
      svg = svg.replace(/fill="[^"]*"/g, `fill="${fillColor.value}"`)
      svg = svg.replace(/stroke="[^"]*"/g, `stroke="${iconColor.value}"`)
      svg = svg.replace(/stroke-width="[^"]*"/g, `stroke-width="${strokeWidth.value}"`)
      break

    case 'multi':
      // 多色模式：根据路径索引应用不同颜色
      const paths = svg.match(/<path[^>]*>/g) || []
      let pathIndex = 0
      svg = svg.replace(/<path[^>]*>/g, (match) => {
        const colorIndex = pathIndex % multiColors.value.length
        pathIndex++
        let newPath = match.replace(/fill="[^"]*"/g, `fill="${multiColors.value[colorIndex]}"`)
        if (!newPath.includes('fill=')) {
          newPath = newPath.replace(/<path/, `<path fill="${multiColors.value[colorIndex]}"`)
        }
        return newPath
      })
      break
  }

  return svg
})

// 重置到原始状态
const resetToOriginal = () => {
  iconSize.value = 22
  strokeWidth.value = 4
  colorMode.value = 'linear'
  iconColor.value = '#333333'
  fillColor.value = '#1890ff'
  multiColors.value = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#f9ca24']
  message.success('已重置到原始状态')
}

// 导出图标
const exportIcon = () => {
  const svgContent = editedIcon.value

  // 创建下载链接
  const blob = new Blob([svgContent], { type: 'image/svg+xml' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `${props.icon.name}_edited.svg`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)

  message.success('图标导出成功')

  // 发送导出事件
  emit('export', {
    originalIcon: props.icon,
    editedSvg: svgContent,
    settings: {
      iconSize: iconSize.value,
      strokeWidth: strokeWidth.value,
      colorMode: colorMode.value,
      iconColor: iconColor.value,
      fillColor: fillColor.value,
      multiColors: [...multiColors.value]
    }
  })
}

// 颜色变化处理
const onColorChange = () => {
  // 颜色变化时的处理逻辑
}

const onFillColorChange = () => {
  // 填充颜色变化时的处理逻辑
}

const onMultiColorChange = () => {
  // 多色配置变化时的处理逻辑
}

const onColorModeChange = () => {
  // 颜色模式变化时的处理逻辑
}

// 设置预设颜色
const setPresetColor = (color) => {
  iconColor.value = color
}

// 初始化
onMounted(() => {
  if (props.icon && props.icon.content) {
    originalIcon.value = props.icon.content
  }
})

// 监听图标变化
watch(
  () => props.icon,
  (newIcon) => {
    if (newIcon && newIcon.content) {
      originalIcon.value = newIcon.content
      resetToOriginal()
    }
  },
  { immediate: true }
)
</script>

<style scoped>
.icon-editor {
  height: 100%;
  background: #fff;
}

.editor-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 24px;
  padding: 24px;
}

.preview-section {
  flex-shrink: 0;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.preview-container {
  display: flex;
  gap: 24px;
  align-items: flex-start;
}

.preview-item {
  flex: 1;
  text-align: center;
}

.preview-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
  font-weight: 500;
}

.preview-box {
  width: 200px;
  height: 200px;
  border: 2px solid #f0f0f0;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
  position: relative;
  margin: 0 auto;
}

.preview-box.original {
  background: linear-gradient(45deg, #f5f5f5 25%, transparent 25%), linear-gradient(-45deg, #f5f5f5 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #f5f5f5 75%), linear-gradient(-45deg, transparent 75%, #f5f5f5 75%);
  background-size: 20px 20px;
  background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
}

.preview-box.edited {
  background: #fff;
  border-color: #1890ff;
}

.icon-display {
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.icon-display :deep(svg) {
  max-width: 120px;
  max-height: 120px;
  transition: all 0.3s ease;
}

.controls-section {
  flex: 1;
  overflow: auto;
}

.control-group {
  margin-bottom: 24px;
}

.control-label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #262626;
  margin-bottom: 8px;
}

.control-content {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.color-picker-group {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.color-picker {
  width: 40px;
  height: 32px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  background: none;
  padding: 0;
}

.color-picker.small {
  width: 24px;
  height: 24px;
}

.preset-color-btn {
  width: 24px;
  height: 24px;
  padding: 0;
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  cursor: pointer;
  min-width: 24px;
}

.multi-color-config {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.multi-color-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.color-label {
  font-size: 12px;
  color: #666;
  min-width: 60px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .preview-container {
    flex-direction: column;
    align-items: center;
  }

  .preview-box {
    width: 150px;
    height: 150px;
  }
}

@media (max-width: 768px) {
  .editor-content {
    padding: 16px;
  }

  .preview-header {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }

  .control-content {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>
